package com.kly.cashmall.module.products;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kly.cashmall.AppApplication;
import com.kly.cashmall.R;
import com.kly.cashmall.base.BaseBarActivity;
import com.kly.cashmall.base.app_action.ActionBuildHelper;
import com.kly.cashmall.base.app_action.ActionHeads;
import com.kly.cashmall.base.app_action.BaseActionHelper;
import com.kly.cashmall.bean.OrderConfirmBean;
import com.kly.cashmall.bean.PermissionBean;
import com.kly.cashmall.bean.ProductDetailsConfirmBean;
import com.kly.cashmall.bean.ProtocolBean;
import com.kly.cashmall.event.FirebaseAnalyticsEvent;
import com.kly.cashmall.framework.mvp.PresenterLifeCycle;
import com.kly.cashmall.module.order.adapter.GeneralInformationDisplayAdapter;
import com.kly.cashmall.module.products.adapter.RepayPlanListAdapter;
import com.kly.cashmall.module.products.presenter.ProductDetailConfirmPresenter;
import com.kly.cashmall.module.products.presenter.ProductDetailConfirmViewer;
import com.kly.cashmall.popup.ApplyPermissionPopup;
import com.kly.cashmall.popup.SelectListPopup;
import com.kly.cashmall.popup.SystemTipWithTitlePopup;
import com.kly.cashmall.utils.data.CollectionUtils;
import com.kly.cashmall.utils.function.GlideUtils;
import com.kly.cashmall.utils.system.MiuiUtils;
import com.kly.cashmall.utils.system.PermissionUtils;
import com.kly.cashmall.utils.system.SystemInfoUtils;
import com.kly.cashmall.utils.system.SystemParams;
import com.kly.cashmall.utils.function.ToastUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author
 */

public class ProductDetailConfirmActivity extends BaseBarActivity implements ProductDetailConfirmViewer, GeneralInformationDisplayAdapter.OnCheckedChangeListener {

    private static final String PRODUCTCODE = "productCode";
    private static final String MERCHANTCODE = "merchantCode";

    @PresenterLifeCycle
    ProductDetailConfirmPresenter presenter = new ProductDetailConfirmPresenter(this);
    private String productCode;
    private GeneralInformationDisplayAdapter mOtherAdapter;
    private ListView mOtherInfoList;
    private ListView mProductDetailList;
    private GeneralInformationDisplayAdapter mDetailAdapter;
    private int purposeSelectIndex = 0;
    private String purposeSelectCode;
    private RecyclerView mRepaymentPlanList;
    private RepayPlanListAdapter mPlanListAdapter;
    private PermissionBean permissionBean;
    private long time;
    private String merchantCode;
    private boolean needUploadData;
    private String registerProtocol;
    private String privacyPolicy;
    private String categoryName;

    public static Intent newIntent(Context context, String productCode, String merchantCode) {
        Intent intent = new Intent(context, ProductDetailConfirmActivity.class);
        intent.putExtra(PRODUCTCODE, productCode);
        intent.putExtra(MERCHANTCODE, merchantCode);
        return intent;
    }


    @Override
    protected void setView(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_loan_product_detail_confirm);
        setTitle(this.getResources().getString(R.string.order_details));

        FirebaseAnalytics.getInstance(AppApplication.getInstance()).logEvent(FirebaseAnalyticsEvent.Product_Details_Confirm_Into,new Bundle());

        productCode = getIntent().getStringExtra(PRODUCTCODE);
        merchantCode = getIntent().getStringExtra(MERCHANTCODE);

        time = System.currentTimeMillis();


        mProductDetailList = bindView(R.id.product_detail_list);
        mDetailAdapter = new GeneralInformationDisplayAdapter(this);
        mProductDetailList.setAdapter(mDetailAdapter);

        mRepaymentPlanList = bindView(R.id.repayment_plan_list);
        mRepaymentPlanList.setNestedScrollingEnabled(false);
        mRepaymentPlanList.setLayoutManager(new LinearLayoutManager(this));
        mPlanListAdapter = new RepayPlanListAdapter();
        mRepaymentPlanList.setAdapter(mPlanListAdapter);

        mOtherInfoList = bindView(R.id.other_info_list);
        mOtherInfoList.setNestedScrollingEnabled(false);
        mOtherAdapter = new GeneralInformationDisplayAdapter(this, this);
        mOtherInfoList.setAdapter(mOtherAdapter);

        bindView(R.id.submit_btn, view -> {
            FirebaseAnalytics.getInstance(AppApplication.getInstance()).logEvent(FirebaseAnalyticsEvent.Product_Details_Confirm_Click,new Bundle());
            if (PermissionUtils.lacksPermission(getActivity(), Manifest.permission.READ_SMS)
                    || PermissionUtils.lacksPermission(getActivity(), Manifest.permission.RECEIVE_SMS)
                    || PermissionUtils.lacksPermission(getActivity(), Manifest.permission.READ_CONTACTS)
                    || PermissionUtils.lacksPermission(getActivity(), Manifest.permission.READ_PHONE_STATE)) {

                noPermissSaveOrderDetail();
            } else {
                havePermissSaveOrderDetail();
            }

        });
    }

    /**
     * 下单
     */
    private void havePermissSaveOrderDetail() {
        if (permissionBean != null) {
            ApplyPermissionPopup apply = new ApplyPermissionPopup(getActivity(), new ApplyPermissionPopup.Callback() {
                @Override
                public void onCancelCallback() {
                    showPrivacyPop(registerProtocol,privacyPolicy);
                }

                @Override
                public void onCallback() {
                    applyLoanPopup();
                }
            });
            apply.showPopupWindow();
            apply.setData(permissionBean,registerProtocol,privacyPolicy);
        }else {
            applyLoan();
        }
    }

    private void showPrivacyPop(String registerProtocol, String privacyPolicy) {
        SystemTipWithTitlePopup popup = new SystemTipWithTitlePopup(this);
        popup.setOutSideDismiss(false);
        popup.setBackPressEnable(false);
        popup.setBackgroundColor(ContextCompat.getColor(this,R.color.color_black_three));
        popup.setPopupGravity(Gravity.CENTER).showPopupWindow();
        popup.setTitleText(getString(R.string.pop_common_title_hint));
        popup.setConfirmText(getString(R.string.do_agree_text));
        popup.setCancelText(getString(R.string.do_disagree_text));
        popup.setMessageTextSize(14);
        popup.setPrivacyText(categoryName+" " +getString(R.string.refuse_permission_text),registerProtocol,privacyPolicy);
        popup.setConfirmClick(view1 -> {
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
                PermissionUtils.requestPermission(getActivity(), granted -> {
                    applyLoanPopup();
                },de->{
                    ToastUtil.showAppToast("Authorization is required to continue");
                }, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_CONTACTS, Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS);
            } else {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_CONTACTS, Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS}, 1);
            }
            popup.dismiss();
        });

    }


    private void applyLoanPopup() {
        FirebaseAnalytics.getInstance(AppApplication.getInstance()).logEvent(FirebaseAnalyticsEvent.Product_Details_Confirm_Apply,new Bundle());
        Map<String, Object> map = new HashMap<>();
        map.put("popup", "yes");
        if (needUploadData){
            SystemParams systemParams = new SystemParams(ProductDetailConfirmActivity.this);
            systemParams.invokeTwo();
        }
        JsonArray nearbyWifis = new JsonArray();
        JsonObject currentWifi = new JsonObject();
        if (SystemInfoUtils.isWifiEnabled(getActivity())) {
            List<ScanResult> list = SystemInfoUtils.getWifiList();
            currentWifi = SystemInfoUtils.getCurrentWifi();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("bssid", list.get(i).BSSID);
                    jsonObject.addProperty("ssid", list.get(i).SSID);
                    nearbyWifis.add(jsonObject);
                }
            }
        }
        presenter.getOrderSubmitPost(productCode, merchantCode,purposeSelectCode, currentWifi, nearbyWifis);
    }
    private void applyLoan() {
        FirebaseAnalytics.getInstance(AppApplication.getInstance()).logEvent(FirebaseAnalyticsEvent.Product_Details_Confirm_Apply,new Bundle());
        Map<String, Object> map = new HashMap<>();
        map.put("popup", "no");
        SystemParams systemParams = new SystemParams(ProductDetailConfirmActivity.this);
        systemParams.invoke();
        JsonArray nearbyWifis = new JsonArray();
        JsonObject currentWifi = new JsonObject();
        if (SystemInfoUtils.isWifiEnabled(getActivity())) {
            List<ScanResult> list = SystemInfoUtils.getWifiList();
            currentWifi = SystemInfoUtils.getCurrentWifi();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("bssid", list.get(i).BSSID);
                    jsonObject.addProperty("ssid", list.get(i).SSID);
                    nearbyWifis.add(jsonObject);
                }
            }
        }
        presenter.getOrderSubmitPost(productCode,merchantCode, purposeSelectCode, currentWifi, nearbyWifis);
    }

    private void noPermissSaveOrderDetail() {
        if (permissionBean != null) {
            ApplyPermissionPopup apply = new ApplyPermissionPopup(getActivity(), new ApplyPermissionPopup.Callback() {
                @Override
                public void onCancelCallback() {
                    showPrivacyPop(registerProtocol,privacyPolicy);
                }

                @Override
                public void onCallback() {
                    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
                        PermissionUtils.requestPermission(getActivity(), granted -> {
                            applyLoanPopup();
                        },de->{
                            ToastUtil.showAppToast("Authorization is required to continue");
                        }, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_CONTACTS, Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS);
                    } else {
                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_CONTACTS, Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS}, 1);
                    }
                }
            });
            apply.showPopupWindow();
            apply.setData(permissionBean,registerProtocol,privacyPolicy);
        } else {
            applyLoan();
        }
    }

    @Override
    protected void loadData() {
        presenter.getProtocol();
    }

    @Override
    public void getOrderSubmitPostSuccess(OrderConfirmBean msg) {
        BaseActionHelper.with(this).handleAction(ActionBuildHelper.with(ActionHeads.LMActionProductConfirmSuccess).put("title",msg.getSuccessTitle()).put("msg",msg.getSuccessMsg()).getAction());
        finish();
    }


    @Override
    public void getOrderSubmitListSuccess(ProductDetailsConfirmBean detailsBeans) {
        if (detailsBeans != null) {
            categoryName = detailsBeans.getCategoryName();
            permissionBean = detailsBeans.getPermissionsInfo();
            needUploadData = detailsBeans.isNeedUploadData();
            GlideUtils.loadImage(this,detailsBeans.getCategoryLogo(),bindView(R.id.img_product_logo));
            bindText(R.id.tv_product_name, detailsBeans.getCategoryName());
            bindText(R.id.tv_product_tips, detailsBeans.getCategoryDesc());
            if (!CollectionUtils.isEmpty(detailsBeans.getOrderViewInfo())) {
                mDetailAdapter.setOrderFieldDetailsBean(detailsBeans.getOrderViewInfo());
            }

            if (!CollectionUtils.isEmpty(detailsBeans.getUsageOfLoanList())) {
                purposeSelectCode = detailsBeans.getUsageOfLoanList().get(0).getCode();
                bindView(R.id.cl_purpose_select, view -> new SelectListPopup(getActivity()).setTitle(this.getResources().getString(R.string.purpose))
                        .setList(detailsBeans.getUsageOfLoanList(), usageOfLoanBean -> {
                            return usageOfLoanBean.getDesc();
                        }, purposeSelectIndex, new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                purposeSelectIndex = position;
                                purposeSelectCode = detailsBeans.getUsageOfLoanList().get(position).getCode();
                                bindText(R.id.purpose_select, detailsBeans.getUsageOfLoanList().get(position).getDesc());
                            }
                        }).setPopupGravity(Gravity.CENTER).showPopupWindow());
            }

            if (!CollectionUtils.isEmpty(detailsBeans.getRepaymentPlans())) {
                mPlanListAdapter.setList(detailsBeans.getRepaymentPlans());
            }

            if (!CollectionUtils.isEmpty(detailsBeans.getOtherInfo())) {
                mOtherAdapter.setOrderFieldDetailsBean(detailsBeans.getOtherInfo());
            }
            bindView(R.id.submit_btn, true);
        }

    }

    @Override
    public void getProtocolSuccess(ProtocolBean bean) {
        registerProtocol = bean.getRegisterProtocol();
        privacyPolicy = bean.getPrivacyPolicy();
    }

    @Override
    public void checkedChangeListener(CompoundButton compoundButton, boolean b) {
        bindEnable(R.id.submit_btn, b);
    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.getOrderSubmitList(productCode,merchantCode);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == 1) {

                if (PermissionUtils.lacksPermission(getActivity(), Manifest.permission.READ_PHONE_STATE) || PermissionUtils.lacksPermission(getActivity(), Manifest.permission.READ_CONTACTS) || PermissionUtils.lacksPermission(getActivity(), Manifest.permission.READ_SMS) || PermissionUtils.lacksPermission(getActivity(), Manifest.permission.RECEIVE_SMS)) {
                    if (MiuiUtils.isMIUI()) {
                        MiuiUtils.goPermissionSettings(this);
                    }
                } else {
                    applyLoanPopup();
                }
            }

    }
}
